# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.template.defaultfilters import pluralize

from tagging.forms import TagField

from models import Project, Release, Screenshot, Video
from utils.forms import UserField

DISALLOWED_PROJECT_NAMES = ("latest",
                            "discussed", 
                            "alphabet", 
                            "random",
                            "create")


def check_unique(model, query, name="name"):
    if model.objects.filter(**query).count():
        raise forms.ValidationError("%s '%s' already taken" % 
                                (name.capitalize(), query[name+"__iexact"]))
    

class ProjectForm(forms.ModelForm):
    # the project creator will be added automatically
    admins = UserField(required=False,
                help_text= ("Comma separated list of usernames. " +
                            "You will be added automatically. (optional)"))
    members = UserField(required=False,
                help_text="Comma separated list of usernames. (optional)")
    tags = TagField(widget=forms.TextInput(attrs={'size':'40'}),
                help_text=('Comma separated, multiple word tags in quotes. ' +
                            'Example: spam,bacon,"foo bar"'))
    
    def clean(self):
        # users cannot be admin and member or doulbe admin
        cleaned_data = super(ProjectForm, self).clean()
        admins = cleaned_data.get("admins") and set(cleaned_data.get("admins")) or []
        cleaned_data["admins"] = list(admins)
        members = cleaned_data.get("members") and set(cleaned_data.get("members")) or []     
        if admins and members:
            members -= admins
        cleaned_data["members"] = list(members)        
        return cleaned_data
    
    def clean_name(self):
        """
        check for restricted project names
        """
        name = self.cleaned_data['name']
        if name in DISALLOWED_PROJECT_NAMES:
            raise forms.ValidationError("Sorry, you cannot use this name!")
#        if Project.objects.filter(name__iexact=name):
#            raise forms.ValidationError("name '%s' already taken" % name)
        return name


class ProjectCreationForm(ProjectForm):
#  not necessary with slug field
#    name = forms.RegexField(regex=r'^\w+$',
#                            error_message = "Project name must contain only " +
#                                            "letters, numbers and underscores.",
#                            help_text="The name of your Project.")
    class Meta:
        model = Project
        exclude = ('raw_description','raw_summary',
                   'creator', 'last_editor',
                   'comment_count', 'slug')
                   
    def clean_name(self):
        name = super(ProjectCreationForm, self).clean_name()
        check_unique(Project, {"name__iexact":name})
        return name
    
class ProjectEditForm(ProjectForm):
    class Meta:
        model = Project
        exclude = ('raw_description','raw_summary',
                   'creator', 'last_editor',
                   'comment_count', 'name', 'slug')

                   
class ReleaseCreationForm(forms.ModelForm):
    class Meta:
        model = Release
        exclude = ('raw_changelog','raw_summary',
                   'creator', 'last_editor',
                   'project', 'slug') 
    
    def clean_version(self):
        version = self.cleaned_data['version']
        check_unique(Release, {"version__iexact":version,
                               "project": self.instance.project}, "version")
        return version                   
                   
                   
class ReleaseEditForm(forms.ModelForm):
    class Meta:
        model = Release
        exclude = ('raw_changelog','raw_summary',
                   'creator', 'last_editor',
                   'project', 'version', 'slug')  
                   
        
class ScreenshotCreationForm(forms.ModelForm):
    class Meta:
        model = Screenshot
        exclude = ('project', 'slug', 'uploaded_by')
        
    def clean_name(self):
        name = self.cleaned_data['name']
        check_unique(Screenshot, {"name__iexact":name, "project":self.project})
        return name
        
class ScreenshotEditForm(forms.ModelForm):
    class Meta:
        model = Screenshot
        exclude = ('project', 'slug', 'uploaded_by',
                   'name')
                   
class VideoCreationForm(forms.ModelForm):
    class Meta:
        model = Video
        fields = ('video_id',)